import { strToDate } from "@/common/util/date";

class TokenHelper {
  token_key: string;
  user_key: string;
  less_fresh_token_sec: number;
  before_fresh_token_sec!: number;

  constructor() {
    this.token_key = this.getTokenKeyName();
    this.user_key = this.getUserKey();
    this.less_fresh_token_sec = this.getLessFreshTokenSec();
  }

  getTokenKeyName() {
    return "access_token_engin";
  }

  getUserKey() {
    return "user_info_engin";
  }

  getLessFreshTokenSec() {
    return 60 * 60 * 24;
  }

  getStorage: any = () => {
    throw new Error("当前方法必须被继承");
  };

  translate(tokenObj: any) {
    return tokenObj;
  }

  __getJsonFromStorage(key: string) {
    try {
      return JSON.parse(this.getStorage().getItem(key));
    } catch (error) {}
    return {};
  }

  __setObjInStorage(key: string, obj: any) {
    this.getStorage().setItem(key, JSON.stringify(obj));
  }

  __getTokenObj() {
    let tokenObj = this.__getJsonFromStorage(this.token_key);
    tokenObj = this.translate(tokenObj);
    return tokenObj;
  }

  getToken = () => {
    const tokenObj = this.__getTokenObj();
    if (tokenObj && tokenObj["accessToken"]) {
      return tokenObj["accessToken"];
    }
  };

  setToken = (tokenObj: any) => {
    this.__setObjInStorage(this.token_key, tokenObj);
  };
  getUserInfo = () => {
    return this.__getJsonFromStorage(this.user_key);
  };

  setUserInfo = (userInfo: any) => {
    this.__setObjInStorage(this.user_key, userInfo);
  };

  validToken = (refreshCallBack: (arg0: any) => void) => {
    try {
      const token_obj = this.__getTokenObj();
      const fresh_token_expire_time = strToDate(
        token_obj["accessRefreshExpiresAt"]
      );
      const nowDateTime = new Date().getTime();
      if (fresh_token_expire_time > nowDateTime) {
        const token_expire_time = strToDate(token_obj["accessTokenExpiresAt"]);
        if(token_expire_time < nowDateTime){
          refreshCallBack(token_obj["accessRefresh"])
        }
        return true
        // if (token_expire_time < nowDateTime) {
        //   if (
        //     (token_expire_time - nowDateTime) / 1000 <
        //     this.before_fresh_token_sec
        //   ) {
        //     refreshCallBack(token_obj["accessRefresh"]);
        //   }
        // }
        // return true;
      }
    } catch (err) {}
    return false;
  };
}

class LocalTokenStrategy extends TokenHelper {
  getStorage = () => {
    return window.localStorage;
  };
}

class SessionTokenStrategy extends TokenHelper {
  getStorage = () => {
    return window.sessionStorage;
  };
}

const localTokenStrategy = new LocalTokenStrategy();

export default localTokenStrategy;
